﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using System.Threading;
using System.Data.OleDb;
using System.Data;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows.Threading;
using System.Collections.ObjectModel;

namespace LogFileParser
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 
    
    public partial class MainWindow : Window,INotifyPropertyChanged
    {
        static Mutex mutex = new Mutex(false, "");
        Microsoft.Office.Interop.Excel.Range range;
        Microsoft.Office.Interop.Excel.Application excelApp;
        public MainWindow()
        {
            InitializeComponent();
            ButtonStatus = true;
        }

        private int valueProgress;

        public int ValueProgress
        {
            get { return valueProgress; }
            set { valueProgress = value; RaisePropertyChanged(() => ValueProgress); }
        }
        
        private string status;

        public string Status
        {
            get { return status; }
            set { status = value; RaisePropertyChanged(() => Status); }
        }
        private bool buttonStatus;

        public bool ButtonStatus
        {
            get { return buttonStatus; }
            set { buttonStatus = value; RaisePropertyChanged(() => ButtonStatus); }
        }
       
        
        List<String> fileNames,LogData,ReadData;
        string writeFileName, writeFileNameNew ,folderLocation,logDir,  content;
        ObservableCollection<string> line = new ObservableCollection<string>();
        int returnValue = 0, rowNo = 2, process = 0, value=0;

        #region"Code logic for selecting the log file"

        private void btnSelect_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.ShowDialog();
            folderLocation = dialog.SelectedPath.ToString();
            fileNames = new List<string>();
            if (Directory.Exists(folderLocation))
            {
                fileNames = (from d in Directory.GetFiles(folderLocation, "*.log")
                             select d).ToList<string>();
            }
            else
            {
                Status = Status + "Invalid Folder Location !!!";
            }



            #region OpenDialog
            //openFileDialog = new OpenFileDialog();
            //openFileDialog.Filter = ParserResource.TEXTFORMAT;
            //openFileDialog.Multiselect = false;
            //openFileDialog.ShowDialog();
            //readFileName = openFileDialog.FileName;
            #endregion
            if (folderLocation != ParserResource.EMPTY)
            {
                txtFilePath.Text = folderLocation;
                btnSelect.IsEnabled = false;                
                btnprocess.IsEnabled = true;
            }
            else
            {
                txtFilePath.Text = ParserResource.NOPATH;

            }

        }
        #endregion

        #region"Code logic for readign the log file"

        public int validate(ObservableCollection<string> text, string startTime, string EndTime)
        {
            
            string dateTime = null;
            if (text != null)
            {
                foreach (var item in text)
                {                    
               
                DateTime date;
                try
                {
                    if (DateTime.TryParse(item.Substring(0, 20), out date))
                    {
                        dateTime = date.ToString();
                    }

                }
                catch (Exception e)
                {
                    goto t;
                }

                if (dateTime != null)
                {
                    if (Convert.ToDateTime(item.Substring(0, 20)) >= Convert.ToDateTime(startTime))
                    {
                        returnValue = 1;
                        if (Convert.ToDateTime(item.Substring(0, 20)) >= (Convert.ToDateTime(EndTime).AddMinutes(1)))
                        {
                            returnValue =2;
                        }
                    }                   
                }
              }
            }
            t:return returnValue;

        }
        public string ReadText(string fileName, string startTime, string endTime, string serverName)
        {
            //Thread.Sleep(5000);
            string path=null;
            switch (serverName)
            {
                case "VAPP01_64":
                    serverName = "f_olf_app01";
                    break;
                case "VAPP02_64":
                    serverName = "f_olf_app02";
                    break;
                case "VAPP03_64":
                    serverName = "f_olf_app03";
                    break;
                case "VAPP04_64":
                    serverName = "f_olf_app04";
                    break;
                case "VAPP05_64":
                    serverName = "f_olf_app05";
                    break;
                case "VAPP06_64":
                    serverName = "f_olf_app06";
                    break;
                case "VAPP07_64":
                    serverName = "f_olf_app07";
                    break;
                case "VAPP08_64":
                    serverName = "f_olf_app08";
                    break;
                case "VAPP09_32":
                    serverName = "f_olf_app09";
                    break;
                case "VAPP10_32":
                    serverName = "f_olf_app10";
                    break;
                default:
                    break;
            }
            if(File.Exists(folderLocation + "\\"+serverName+".log"))
            {
                StreamReader reader = new StreamReader(folderLocation + "\\" + serverName + ".log");
                                
                line = new ObservableCollection<string>();

                line.Add(reader);
	            
                foreach (var item in line)
                {
                
                value = validate(line,startTime,endTime);
                       
                         if(value==1)
                         {
                             content = content + item + "\r\n";
                         }
                         else if(value==2)
                         {
                            path = WriteLogFile(content, fileName);                                    
                            content = null;
                            writeFileName = null;                            
                            reader.Close();
                            returnValue = 0;                            
                            break;
                         }
            }
            if (value == 0 || returnValue != 0)
            {
                path = WriteLogFile(content, fileName);
                content = null;
                writeFileName = null;
                reader.Close();
                returnValue = 0;                
            }

            value = 0;
             
            }
            
            else
            {
                Status = Status + "Log File- " + serverName + "- Not Found\r\n";
            }
                
            return path;
        }
        
        public void ExcelLogWritter(string fileName,int rowNo)
        {
            Status = Status + "Writing Log to Excel - Started For "+ fileName +"........ \r\n";
            string LogDetailsFilename = "LogDetails.xlsx";
            excelApp = new Microsoft.Office.Interop.Excel.Application();
            excelApp.DisplayAlerts = false;
            Microsoft.Office.Interop.Excel.Workbook workBook = excelApp.Workbooks.Open(folderLocation + "\\" + LogDetailsFilename,2,false);
            
            Microsoft.Office.Interop.Excel.Worksheet workSheet = workBook.Worksheets[1];
             
            range = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowNo,6];

            workSheet.Shapes.AddOLEObject(Filename: fileName, Height: range.Height, Width: range.Width, Left: range.Left, Top: range.Top);
           
            workBook.Save();
            workBook.Close();
            excelApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
            GC.Collect();
            
            Status = Status + "Writing Log to Excel - Complete........ \r\n";            
        }                          
        #endregion

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            WindowClose();            
        }

        #region"Code logic for writing the file to another log file"

        public string WriteLogFile(string content, string fileName)
        {

            #region fileWritter
            //writeFileName = readFileName + "_Success_" + date.Day + date.Month + date.Year;


            //if (writeFileName != ParserResource.EMPTY)
            //{
            //    StreamWriter writer = new StreamWriter(writeFileName);
            //    writer.WriteLine(Success);
            //    writer.Close();
            //}


            
            //writeFileName = readFileName + "_Log_" + date.Day + date.Month + date.Year;

            //foreach (var name in fileNames)
            //{
            //    if (name == fileName)
            //    {
            //        writeFileName = name;
            //    }
            //}
#endregion            
            writeFileName = logDir + "\\" + fileName +".txt";
            int i = 0;     
            while (File.Exists(writeFileName))
            {
                writeFileName = logDir + "\\" + fileName + i++ + ".txt";
            }

            if (writeFileName != null)
            {
                StreamWriter writer = new StreamWriter(writeFileName);
                writer.WriteLine(content);
                writer.Close();
            }
            //LogData.Add(writeFileName);
            Status = Status + "\n Success Data Save to" + writeFileName + "\r\n";
            process = 0;
            
           
            return writeFileName;          
        }

        #endregion

        #region"Code logic for calling the close Method the log file"

        private void WindowClose()
        {
            
            MessageBoxResult result = MessageBox.Show(ParserResource.CONTINUEMESSAGE, ParserResource.INFORMATION, MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.No)
            {
               this.Close();             
            }
            else
            {
                Status = Status = ParserResource.EMPTY;
                txtFilePath.Text = ParserResource.EMPTY;
               
                saveProgressBar.Value = 0;
                btnSelect.IsEnabled = true;
            }
        }
       
        #endregion       

        private void btnprocess_Click(object sender, RoutedEventArgs e)
        {
            
            saveProgressBar.Value = 10;
            btnSelect.IsEnabled = false;
            btnprocess.IsEnabled = false;
            ButtonStatus = false;
            string LogDetailsFilename = "LogDetails.xlsx";
            if (File.Exists(folderLocation + "\\" + LogDetailsFilename))
            {
                //Status = Status + "Processing BG Log Files\r\n";      
                Status = Status + "LogDetails.xlsx - Found \r\n";
                Status = Status + "Processing Data........ \r\n";
               

                btnSelect.IsEnabled = false;
                ValueProgress = 20;
                ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessRequest));
                
                
            }
            else
            {
                Status = Status + "LogDetails.xlsx - Not Found \r\n";
                Status = Status + "Please check if file exists \r\n";
                btnSelect.IsEnabled = true;
            }                        
        }       

        void ProcessRequest(object state)
        {
            if (Directory.Exists(folderLocation + "\\Logs"))
            {
                string[] fileNames = Directory.GetFiles(folderLocation + "\\Logs");
                foreach (var names in fileNames)
                {
                    File.Delete(names);

                }
                Directory.Delete(folderLocation + "\\Logs");
            }

            Directory.CreateDirectory(folderLocation + "\\Logs");
            logDir = folderLocation + "\\Logs";

            #region
            OleDbConnection connection = new OleDbConnection();
            OleDbCommand command = new OleDbCommand();
            LogData = new List<string>();
            string LogDetailsFilename1 = "LogDetails.xlsx";

            connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + folderLocation + "\\" + LogDetailsFilename1 + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
            command.CommandText = "select * from [Sheet1$]";
            command.Connection = connection;
            connection.Open();
            using (OleDbDataReader reader = command.ExecuteReader())
            {

                while (reader.Read())
                {
                    if (reader.FieldCount > 0)
                    {
                        Status = Status + "Processing " + reader[3].ToString() + "-" + reader[4].ToString() + "\r\n";

                        LogData.Add(ReadText(reader[3].ToString(), reader[0].ToString(), reader[1].ToString(), reader[2].ToString()));

                    }                    
                }

                reader.Close();
            }
            connection.Close();
            ValueProgress = 60;
                       
            foreach (var item in LogData)
            {
                if (item != null)
                {
                    StreamReader reader = new StreamReader(item);

                    if (reader.ReadLine() != "")
                    {
                        ExcelLogWritter(item, rowNo++);
                    }
                    else
                    {
                        rowNo++;
                    }
                } 
            }

            LogData.Clear();
            ValueProgress = 80;
            WriteLogFile(Status, "StatusLog");
            ValueProgress =100;
            ButtonStatus = true;
            #endregion           
            
        }
       

        #region Properties Notification
       


        protected void RaisePropertyChanged<T>(Expression<Func<T>> action)
        {
            var propertyName = GetPropertyName(action);
            RaisePropertyChanged(propertyName);
        }

        private static string GetPropertyName<T>(Expression<Func<T>> action)
        {
            var expression = (MemberExpression)action.Body;
            var propertyName = expression.Member.Name;
            return propertyName;
        }

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        private void txtView_TextChanged(object sender, TextChangedEventArgs e)
        {
            txtView.ScrollToEnd();
        }

    }
    
}
